package com.goldcn.orderborrow.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.goldcn.common.CommonTools;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ErpBorrowInterfaceCfg;
import com.goldcn.enumeration.ErpInterfaceCfgEnum;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.goods.dao.GoodsInfoMapper;
import com.goldcn.goods.dto.GoodsInfoWithSkuDto;
import com.goldcn.goods.dto.PageInfo;
import com.goldcn.orderborrow.dao.GoodsCartBorrowMapper;
import com.goldcn.orderborrow.dto.GoodsCartBorrowDto;
import com.goldcn.orderborrow.dto.UpdateGoodsCartBorrowDto;
import com.goldcn.orderborrow.model.GoodsCartBorrow;
import com.goldcn.orderborrow.vo.GoodsCartBorrowVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:借货购物车业务类
 * @Author Tim Peng
 * @date 2017-4-19 18:29:10
 * @version V1.0
 */
@Service
public class GoodsCartBorrowService {

    @Autowired
    private GoodsCartBorrowMapper goodsCartBorrowMapper;
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;
    @Autowired
    ErpBorrowInterfaceCfg erpBorrowInterfaceCfg;
    @Autowired
    RestTemplate restTemplate;

    /**
     * 添加商品至我的购物车
     * @param goodsCartBorrowVo
     * @return
     */
    @Transactional
    public Object addMyShoppingCart(GoodsCartBorrowVo goodsCartBorrowVo){
        if(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SELFCOMPANYID.getCode()).indexOf(goodsCartBorrowVo.getSellerID().toString())<0){//限制供应商
            throw new ServiceException("暂不支持该供应商借货", RestConst.ErrorCode.FORM_FAIL);
        }
        //查询商品信息
        GoodsInfoWithSkuDto goodsSku=goodsInfoMapper.selectBySkuID(goodsCartBorrowVo.getSkuID());
        if(goodsSku==null){
            throw CommonTools.createException(ErrorCodeEnum.goodsNoExist);
        }
        if(goodsSku.getInventory()<goodsCartBorrowVo.getQty()){
            throw CommonTools.createException(ErrorCodeEnum.goodsInventoryShortage);
        }
        //插入前操作
        GoodsCartBorrow cart=this.insertCartBefore(goodsCartBorrowVo,goodsSku);
        if(cart.getId()==null){
            cart.setId(IdGen.get().nextId());
            return goodsCartBorrowMapper.insertSelective(cart);
        }else{
            UpdateGoodsCartBorrowDto updateCart=new UpdateGoodsCartBorrowDto();
            BeanUtils.copyProperties(cart,updateCart);
            return goodsCartBorrowMapper.updateGoodsCartInfo(updateCart);
        }
    }

    @Transactional
    private GoodsCartBorrow insertCartBefore(GoodsCartBorrowVo goodsCartBorrowVo,GoodsInfoWithSkuDto goodsSku) {
        GoodsCartBorrow cart= new GoodsCartBorrow();
        //查询购物车是否有该商品
        List<GoodsCartBorrow> goodsCarts=goodsCartBorrowMapper.selectSkuExistInCart(goodsCartBorrowVo.getUserID(),
                goodsCartBorrowVo.getSkuID());
        if(goodsCarts.size()>1) {//合并
            int total=0;
            List<Long> deCarts=new ArrayList<Long>();
            for(GoodsCartBorrow goodsCart:goodsCarts){
                total+=goodsCart.getQty();
                deCarts.add(goodsCart.getId());
            }
            cart.setId(deCarts.get(0));
            deCarts.remove(0);
            BeanUtils.copyProperties(goodsCartBorrowVo,cart);
            cart.setAddTime(System.currentTimeMillis());
            cart.setGoodsID(goodsSku.getGoodsID());
            cart.setQty(cart.getQty()+total);
            goodsCartBorrowMapper.deleteByPrimaryKey(deCarts);
        }else if(goodsCarts.size()==1){
            cart.setId(goodsCarts.get(0).getId());
            BeanUtils.copyProperties(goodsCartBorrowVo,cart);
            cart.setAddTime(System.currentTimeMillis());
            cart.setGoodsID(goodsSku.getGoodsID());
            if(cart.getQty()+goodsCarts.get(0).getQty()>goodsSku.getInventory()){
                throw CommonTools.createException(ErrorCodeEnum.goodsSkuNoInventory);
            }else{
                cart.setQty(cart.getQty()+goodsCarts.get(0).getQty());
            }
        }else{
            BeanUtils.copyProperties(goodsCartBorrowVo,cart);
            cart.setAddTime(System.currentTimeMillis());
            cart.setGoodsID(goodsSku.getGoodsID());
        }
        return cart;
    }

    /**
     * 从购物车移除我的商品(批量)
     * @param ids
     * @return
     */
    public Object removeMyShoppingCart(List<Long> ids){
        return goodsCartBorrowMapper.deleteByPrimaryKey(ids);
    }

    /**
     * 清空购物车
     * @param userID
     * @return
     */
    public Object clearMyShoppingCart(Long userID){
        return goodsCartBorrowMapper.deleteByUserID(userID);
    }

    /**
     * 查询我的购物车
     * @param userID
     * @return
     */
    public Object queryMyShoppingCart(Long userID,Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);//分页初始化
        Page page=(Page) goodsCartBorrowMapper.selectByUserIDorCartID(userID,null);
        return new PageInfo(page,page.getPages(),page.getTotal());
    }

    /**
     * 查询我的购物车
     * @param id
     * @return
     */
    public GoodsCartBorrowDto querySingleMyShoppingCart(Long id){
        List<GoodsCartBorrowDto> cartDtos=goodsCartBorrowMapper.selectByUserIDorCartID(null,id);
        return cartDtos.size()==0?null:cartDtos.get(0);
    }

    /**
     * 修改购物车中商品信息（数量）
     * @param goodsCarts
     * @return
     */
    @Transactional
    public Object updateGoodsCartInfo(List<UpdateGoodsCartBorrowDto> goodsCarts) {
        int result=0;
        for(UpdateGoodsCartBorrowDto goodsCart:goodsCarts){
            //判断库存是否充足
            Integer inventory=goodsCartBorrowMapper.selectInventoryByCartID(goodsCart.getId());
            if(null!=inventory&&inventory>=goodsCart.getQty()){
                result+=goodsCartBorrowMapper.updateGoodsCartInfo(goodsCart);
            }else{
                throw CommonTools.createException(ErrorCodeEnum.goodsInventoryShortage,
                        "库存上限:"+inventory);
            }
        }
        return result;
    }

    public Object retInventory(Long skuID){
        GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(skuID);
        if(null==goodsInfoWithSkuDto){return 0;}
        return goodsInfoWithSkuDto.getInventory();
    }

}
